package com.cy.store.controller;

import com.cy.store.entity.User;
import com.cy.store.service.IUserService;
import com.cy.store.service.ex.InsertException;
import com.cy.store.service.ex.UsernameDuplicatedException;
import com.cy.store.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;


/**
 * @auther 尚智江
 * @Date 2022/7/17 0:49
 */
@RestController// @RestController == @Controller + @ResponseBody
@RequestMapping("/users")
public class UserController extends BaseController{
    @Autowired
    private IUserService userService;

    @RequestMapping("/reg")
    //@ResponseBody// 此方法的响应结果以 json格式进行数据响应给前端
    public JSONResult<Void> reg(User user) {
        userService.reg(user);
        return new JSONResult<>(OK);
    }
    @RequestMapping("login")
    public JSONResult<User> login(String username, String password ,HttpSession session){
        User user = userService.login(username,password);
        // 向session对象中完成数据绑定（session全局）
        session.setAttribute("uid",user.getUid());
        session.setAttribute("username",user.getUsername());
        // 获取session中绑定的数据
        System.out.println(getuidFromSession(session));
        System.out.println(getUsernameFromSession(session));
        return new JSONResult<>(OK,user);
    }
    /*
    @RequestMapping("/reg")
    //@ResponseBody// 此方法的响应结果以 json格式进行数据响应给前端
    public JSONResult<Void> reg(User user){
        // 创建 响应结果对象
        JSONResult<Void> result = new JSONResult<>();
        try {
            userService.reg(user);
            result.setState(200);
            result.setMessage("注册成功");
        } catch (UsernameDuplicatedException e) {
            result.setState(4000);
            result.setMessage("用户名被占用");
        } catch (InsertException e){
            result.setState(5000);
            result.setMessage("注册时产生未知异常");
        }
        return result;
    }

     */
}
